package com.zzyl.serve.service.impl;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.core.domain.entity.SysUser;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.interceptor.MyMetaObjectHandler;
import com.zzyl.serve.domain.Device;
import com.zzyl.serve.dto.AlertDataDto;
import com.zzyl.serve.mapper.DeviceDataMapper;
import com.zzyl.serve.mapper.DeviceMapper;
import com.zzyl.serve.service.IDeviceService;
import com.zzyl.serve.vo.AlertDataVo;
import com.zzyl.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.serve.mapper.AlertDataMapper;
import com.zzyl.serve.domain.AlertData;
import com.zzyl.serve.service.IAlertDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;

import static com.zzyl.framework.interceptor.MyMetaObjectHandler.loadUserId;

/**
 * 报警数据Service业务层处理
 * 
 * @author iteheima
 * @date 2025-03-18
 */
@Service
public class AlertDataServiceImpl extends ServiceImpl<AlertDataMapper, AlertData> implements IAlertDataService
{
    @Autowired
    private AlertDataMapper alertDataMapper;
    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 查询报警数据
     * 
     * @param id 报警数据主键
     * @return 报警数据
     */
    @Override
    public AlertData selectAlertDataById(Long id)
    {
        return getById(id);
    }


    /**
     * 新增报警数据
     * 
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int insertAlertData(AlertData alertData)
    {
        return save(alertData) ? 1 : 0;
    }

    /**
     * 批量删除报警数据
     * 
     * @param ids 需要删除的报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除报警数据信息
     * 
     * @param id 报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }



    /**
     * 查询报警数据列表
     *
     * @return 报警数据
     */
    @Override
    public List<AlertData> selectAlertDataList(AlertDataDto dto)
    {

        LocalDateTime startTime = dto.getStartTime();
        LocalDateTime endTime = dto.getEndTime();
        String dName = dto.getDeviceName();
        Long userId = MyMetaObjectHandler.loadUserId();

        List<AlertData> alertDataList = alertDataMapper.selectList(new LambdaQueryWrapper<AlertData>()
                .eq(!StringUtils.isBlank(dName), AlertData::getDeviceName, dName)
                // 添加权限控制
                .eq(userId != null, AlertData::getUserId, userId)
                .eq(dto.getStatus() != null, AlertData::getStatus, dto.getStatus())
                .between(startTime != null && endTime != null, AlertData::getCreateTime, startTime, endTime));

/*        alertDataList.forEach(item -> {
            String deviceName = item.getDeviceName();
            item.setNickName(deviceName);
            String iotId = item.getIotId();
            //681d6a459314d1185119f67a_yd002
            String devName = iotId.split("_")[1];
            item.setDeviceName(devName);
        });*/
        alertDataList.forEach(item -> {
            String iotId = item.getIotId();
            item.setNickName( iotId.split("_")[1]);
        });
        return alertDataList;
    }
    @Autowired
    ISysUserService sysUserService;

    /**
     * 处理报警数据
     */
    @Override
    public int handleAlertData(AlertData alertData)
    {
        // 非空校验
        if(ObjectUtil.isEmpty(alertData)) {
            throw new BaseException("处理内容为空");
        }
        // 获取报警数据对象
        Long id = alertData.getId();
        AlertData theAlertData = alertDataMapper.selectAlertDataById(id);

        // 获取相同数据
        Long userId = MyMetaObjectHandler.loadUserId();
        SysUser sysUser = sysUserService.selectUserById(userId);

        // 查询其他用户的相同数据
        String iotId = theAlertData.getIotId();
        Date createTime = theAlertData.getCreateTime();

        List<AlertData> alertDataList = alertDataMapper.selectList(new LambdaQueryWrapper<AlertData>()
                .eq(AlertData::getIotId, iotId)
                .eq(AlertData::getCreateTime, createTime));
        alertDataList.forEach( theSameAlertData ->  {
            // 非空校验处理结果
            if(!StringUtils.isBlank(alertData.getProcessingResult())) {
                theSameAlertData.setProcessingResult(alertData.getProcessingResult());
            }
            // 非空校验处理时间
            if(alertData.getProcessingTime() != null) {
                theSameAlertData.setProcessingTime(alertData.getProcessingTime());
            }
            // 保存其他字段
            theSameAlertData.setProcessorId(sysUser.getUserId());
            theSameAlertData.setProcessorName(sysUser.getNickName());
            theSameAlertData.setStatus(1);
        });

        return updateBatchById(alertDataList) ? 1 : 0;
    }
}
